package com.hdu.h_health.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bmob.BTPFileResponse;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadListener;
import com.hdu.h_health.R;
import com.hdu.h_health.bean.User;
import com.hdu.h_health.common.BaseActivity;
import com.hdu.h_health.event.UpdateEvent;
import com.hdu.h_health.model.UserModel;
import com.hdu.h_health.utils.CacheUtils;
import com.hdu.h_health.utils.ViewUtils;
import com.hdu.h_health.widget.NavigationView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.datatype.BmobFile;

/**
 * 编辑资料
 * Created by 612 on 2016/3/8.
 */
public class SetMyInfoActivity extends BaseActivity {
    @Bind(R.id.navView)
    NavigationView navView;
    @Bind(R.id.iv_avatar)
    ImageView ivAvatar;
    @Bind(R.id.layout_avatar)
    RelativeLayout layoutAvatar;
    @Bind(R.id.tv_username)
    TextView tvUsername;
    @Bind(R.id.layout_username)
    RelativeLayout layoutUsername;
    @Bind(R.id.tv_nickname)
    TextView tvNickname;
    @Bind(R.id.layout_nickname)
    RelativeLayout layoutNickname;
    @Bind(R.id.tv_email)
    TextView tvEmail;
    @Bind(R.id.layout_email)
    RelativeLayout layoutEmail;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.layout_sex)
    RelativeLayout layoutSex;
    @Bind(R.id.tv_summary)
    TextView tvSummary;
    @Bind(R.id.layout_summary)
    RelativeLayout layoutSummary;

    private static final int AVATAR = 0;
    private static final int NICKNAME = 1;
    private static final int EMAIL = 2;
    private static final int SEX = 3;
    private static final int SUMMARY = 4;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setmyinfo);
        //检测是否登录
        boolean isLogin = UserModel.getInstance().checkIsLogin(this);
        if (isLogin) {
            setMyInfo();
        } else {

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setMyInfo();
        Log.i("Main", "onResume: ");
    }

    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
        navView.setTv_title("我的资料");
        navView.getIv_left().setImageResource(R.drawable.ic_keyboard_arrow_left_white_36dp);
        navView.setClickListener(new NavigationView.ClickCallBack() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
//                startActivity(new Intent(getBaseContext(), EditSecretActivity.class));
            }
        });
    }


    @OnClick({R.id.layout_avatar, R.id.layout_username, R.id.layout_nickname, R.id.layout_email, R.id.layout_sex, R.id.layout_summary})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.layout_avatar:
                showAlbumDialog();
                break;
            case R.id.layout_username:
                break;
            case R.id.layout_nickname:
                intent = new Intent(this, EditMyInfoActivity.class);
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
            case R.id.layout_email:
                intent = new Intent(this, EditMyInfoActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.layout_sex:
                showSexDialog();
//                intent = new Intent(this, EditMyInfoActivity.class);
//                intent.putExtra("type", 2);
//                startActivity(intent);
                break;
            case R.id.layout_summary:
                intent = new Intent(this, EditMyInfoActivity.class);
                intent.putExtra("type", 3);
                startActivity(intent);
                break;
        }
    }

    //设置用户信息
    private void setMyInfo() {
        User user = UserModel.getInstance().getCurrentUser();
        ViewUtils.setPic(user.getAvatar(), R.mipmap.head, ivAvatar);
        tvUsername.setText(user.getUsername());
        tvNickname.setText(user.getNick());
        tvEmail.setText(user.getEmail());
        if (user.getSex()) {
            tvSex.setText("男");
        } else {
            tvSex.setText("女");
        }
        tvSummary.setText(user.getSummary());
    }


    //显示性别选择对话框(单选)
    private void showSexDialog() {
        final User user = new User();
        String items[] = {"男", "女"};
        final int position;
        if (tvSex.getText().equals("男")) {
            position = 0;
        } else if (tvSex.getText().equals("女")) {
            position = 1;
        } else {
            position = -1;
        }
        new AlertDialog.Builder(this)
                .setTitle("性别")
                .setSingleChoiceItems(items, position, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            user.setSex(true);
                            tvSex.setText("男");
                        } else {
                            user.setSex(false);
                            tvSex.setText("女");
                        }
                        UserModel.getInstance().updateMyInfo(SEX, getBaseContext(), user);
                        dialog.dismiss();
                    }
                }).show();
    }

    public void onEventMainThread(UpdateEvent event) {
        int type = event.getType();
        String msg = event.getMessage();
        switch (type){
            case SEX:
                Toast.makeText(this, "性别"+msg, Toast.LENGTH_SHORT).show();
                break;
            case EMAIL:
                break;
            case NICKNAME:
                break;
            case SUMMARY:
                break;
            case AVATAR:
                Toast.makeText(this, "头像"+msg, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    //显示头像选择框
    String dateTime;//日期
    AlertDialog albumDialog;

    private void showAlbumDialog() {
        albumDialog = new AlertDialog.Builder(this).create();
        albumDialog.setCanceledOnTouchOutside(true);
//        View v = LayoutInflater.from(this).inflate(R.layout.dialog_usericon, null, false);
        View v = LayoutInflater.from(this).inflate(R.layout.dialog_usericon, null);
        albumDialog.show();
        albumDialog.setContentView(v);
        albumDialog.getWindow().setGravity(Gravity.CENTER);
        TextView albumPic = (TextView) v.findViewById(R.id.album_pic);
        TextView cameraPic = (TextView) v.findViewById(R.id.camera_pic);
        albumPic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                albumDialog.dismiss();
                Date date = new Date(System.currentTimeMillis());
                dateTime = date.getTime() + "";
                getAvatarFromAlbum();
            }
        });
        cameraPic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                albumDialog.dismiss();
                Date date = new Date(System.currentTimeMillis());
                dateTime = date.getTime() + "";
                getAvatarFromCamera();
            }
        });
    }

    //拍照获取图片
    private void getAvatarFromCamera() {
        File file = new File(CacheUtils.getCacheDirectory(this, true, "icon") + dateTime);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri uri = Uri.fromFile(file);
        Log.e("uri", uri + "");
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //下面这句指定调用相机拍照后的照片存储的路径,这样通过这个uri就可以得到这个照片了
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        //调用相机应用
        startActivityForResult(cameraIntent, 1);//1--是用作判断返回结果的标识
    }

    //从相册获取图片
    private void getAvatarFromAlbum() {
        Intent album = new Intent(Intent.ACTION_GET_CONTENT);
        // 来自相册
//        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        album.setType("image/*");//设置数据类型，如要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
        startActivityForResult(album, 2);//2--是用作判断返回结果的标识
    }

    String iconUrl;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1://从相机返回的图像
                String files = CacheUtils.getCacheDirectory(this, true, "icon") + dateTime;
                File file = new File(files);
                if (file.exists() && file.length() > 0) {
                    Uri uri = Uri.fromFile(file);
                    clipPhoto(uri);
                } else {
                }
                break;
            case 2://从图库返回的图像
                if (data == null) {
                    return;
                }
                clipPhoto(data.getData());
                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap bitmap = extras.getParcelable("data");
                        iconUrl = saveToSdCard(bitmap);
                        ivAvatar.setImageBitmap(bitmap);
                        updateIcon(iconUrl);
                    }
                }
                break;

        }
    }

    //调用Android自身的图片裁剪功能
    public void clipPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //选择需图片类型，如果是*表明所有类型的图片
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop = true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例，这里设置的是正方形（长宽比为1:1）
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 120);
        intent.putExtra("outputY", 120);
        //裁剪时是否保留图片的比例，这里的比例是1:1
        intent.putExtra("scale", true);
        //TODO 尚未知
        intent.putExtra("scaleUpIfNeeded", true);
        //是否将数据保留在Bitmap中返回
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);//3--是用作判断返回结果的标识
    }

    //存储到手机内存中
    public String saveToSdCard(Bitmap bitmap) {
        //图像文件名称
        String files = CacheUtils.getCacheDirectory(this, true, "icon") + dateTime + "_12.jpg";
        File file = new File(files);
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i(TAG, file.getAbsolutePath());
        return file.getAbsolutePath();
    }

    //上传头像文件
    private void updateIcon(String avatarPath) {
        BTPFileResponse response = BmobProFile.getInstance(this).upload(avatarPath, new UploadListener() {
            @Override
            public void onSuccess(String s, String s1, BmobFile bmobFile) {
                // s：文件名（带后缀），这个文件名是唯一的，开发者需要记录下该文件名，方便后续下载或者进行缩略图的处理
                // s1：文件地址
                // bmobFile:BmobFile文件类型，`V3.4.1版本`开始提供，用于兼容新旧文件服务。
                //注：若上传的是图片，url地址并不能直接在浏览器查看（会出现404错误），需要经过`URL签名`得到真正的可访问的URL地址,当然，`V3.4.1`的版本可直接从'file.getUrl()'中获得可访问的文件地址。
                User updateUser = new User();
                Log.i(TAG, "onSuccess: " + bmobFile.getUrl());
                updateUser.setAvatar(bmobFile.getUrl());//设置头像url
                UserModel.getInstance().updateMyInfo(AVATAR,getBaseContext(), updateUser);//更新个人信息
            }

            @Override
            public void onProgress(int i) {

            }

            @Override
            public void onError(int i, String s) {
                toast("头像更新失败，请检查网络~");
                Log.i(TAG, "onError: 文件上传失败");
            }
        });
    }
}
